package com.secf.service.action.hpy.hys.day87;

import java.sql.*;

/**
 * @Author bug菌
 * @Source 公众号：猿圈奇妙屋
 * @Date 2024年7月9日15:01:32
 */
public class TestExecuteQuery {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/review_db?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8"; // 数据库连接URL
    private static final String USER = "root"; // 数据库用户名
    private static final String PASSWORD = "123456"; // 数据库密码

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 注册JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            stmt = conn.createStatement();
            String sql = "SELECT * FROM user";
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                // 打印结果
                System.out.println("id: " + id + ", name: " + name + ", sex: " + sex);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源，避免资源泄露
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

